<?php

namespace Home\Controller;

use Home\Model\SigninModel;
use Think\Controller;

class SigninController extends BaseController
{
    public function index()
    {
        $sign = new SigninModel(); // 实例化User对象
        $query = $sign;
        $count = $query->count();// 查询满足要求的总记录数
        $Page = new \Think\Page($count, 10);// 实例化分页类 传入总记录数和每页显示的记录数(25)
        $show = $Page->show();// 分页显示输出
        // 进行分页数据查询 注意limit方法的参数要使用Page类的属性
        $list = $query->order('create_time')->limit($Page->firstRow . ',' . $Page->listRows)->select();

        $map['stu_id'] = $this->user['id'];
        $result = $sign->where($map)->order('create_time', 'desc')->select();
        if ($result) {
            if (date('Y-m-d', $result[0]['create_time']) == date('Y-m-d', time())) {
                $this->assign('isSign', 1);
            } else {
                $this->assign('isSign', 0);
            }
        }


        $this->assign('list', $list);// 赋值数据集
        $this->assign('page', $show);// 赋值分页输出
        $this->display(); // 输出模板
    }

    /**
     * 签到
     */
    public function sign()
    {
        $s = new SigninModel(); // 实例化User对象

        if ($this->user['role'] != 3) {
            $this->retError('只有学生才能签到');
        }


        $map['stu_id'] = $this->user['id'];
        $result = $s->where($map)->order('create_time', 'desc')->select();
        if ($result) {
            if (date('Y-m-d', $result[0]['create_time']) == date('Y-m-d', time())) {
                $this->retError('今日已签到');
            }
        }

        $insertModel = M('Signin');
        $data['stu_id'] = $this->user['id'];
        $data['create_time'] = time();
        $data['update_time'] = time();
        $insertModel->create($data);
        $result = $insertModel->add();
        if ($result) {
            $this->retSuccess();
        } else {
            $this->retError('签到失败，系统错误');
        }
    }
}